package org.wll.service.impl;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.wll.dto.DeptEmpDto;
import org.wll.entity.Department;
import org.wll.reporsity.DepartmentRepository;
import org.wll.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wll.util.MapUtil;

import java.util.*;

@Service

public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    DepartmentRepository deptRepository;

    @Override
    public Department findDeptById(Integer eid) {
        Optional<Department> department = deptRepository.findById(eid);
        return department.orElse(null);
    }

    @Override
    public List<Department> findAllDepts() {
        return deptRepository.findAll();
    }

    @Override
    public Department addDept(Department dept) {
        return deptRepository.save(dept);
    }

    @Override
    public Department updeDept(Department Dept) {
        return deptRepository.save(Dept);
    }

    @Override
    public void deleteDeptById(Integer eid) {
        deptRepository.deleteById(eid);
    }

    /**
     * 纯 sql语句实现 多表查询
     * 处理查询回来的数据 和 实体对象绑定
     *
     */
    @Override
    public List<DeptEmpDto> findDeptAllEmpByDid(Integer did) {
        List<DeptEmpDto> list = null;
        List<Map> deptAllEmpByDid = deptRepository.findDeptAllEmpByDid(did);
        try {
            if (deptAllEmpByDid != null && deptAllEmpByDid.size() > 0) {
                list = new ArrayList<>();
                for (Map map : deptAllEmpByDid) {
                    list.add((DeptEmpDto) MapUtil.mapToObject(map, DeptEmpDto.class));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    @Override
    public Page<Map> findDeptAllEmpPageByDid(Integer did, Pageable pageable) {
        Page<Map> page = deptRepository.findDeptAllEmpPageByDid(did, pageable);
        return page;
    }


    @Override
    public Object findDeptAllEmpPage2ByDid(Integer did, Integer pageNumber, Integer pageSize) {
        List<Map> list = null;
        int start = 0;
        int end = 10;
        if(pageNumber != null && pageNumber > 1){
            start = (pageNumber - 1) * pageSize;
            end = pageNumber * pageSize;
        }
        Integer count =  deptRepository.findDeptAllEmpPageByDidCount(did);
        if(count > 0){
            list = deptRepository.findDeptAllEmpPage2ByDid(did, start, end);
        }
        Map map = new HashMap<>();
        map.put("pageNumber", pageNumber);
        map.put("pageSize", pageSize);
        map.put("total", count);
        map.put("data", list);
        return map;
    }
}
